package com.exthirteen.textgamescript.websocket;

import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.Map;

/**
 * <p>
 * 默认的socket客户端
 * </p>
 *
 * @author exthirteen
 * @since 2022/9/22
 */
@Slf4j
class DefaultWebSocketClient<T> extends WebSocketClient {

    /**
     * 监听器
     */
    private final WebSocketClientListener listener;

    public DefaultWebSocketClient(String url,WebSocketClientListener listener) {
        super(URI.create(url),new Draft_6455());
        this.listener = listener;
    }

    public DefaultWebSocketClient(String url, Map<String, String> httpHeaders,WebSocketClientListener listener) {
        super(URI.create(url),new Draft_6455(),httpHeaders);
        this.listener = listener;
    }

    public DefaultWebSocketClient(String url, Map<String, String> httpHeaders, int connectTimeout,WebSocketClientListener listener) {
        super(URI.create(url),new Draft_6455(),httpHeaders,connectTimeout);
        this.listener = listener;
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        log.info("[Socket客户端] 监听到来自: {} 的握手成功信息",getURI().getHost());
        this.listener.onOpen(handshakedata);
    }

    @Override
    public void onMessage(String message) {
        log.info("[Socket客户端] 监听到来自: {} 的消息 : {}",getURI().getHost(),message);
        this.listener.onMessage(message);
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        log.error("[Socket客户端] 监听到与 {} 断开连接",getURI().getHost());
        this.listener.onClose(code,reason,remote);
    }

    @Override
    public void onError(Exception ex) {
        log.error("[Socket客户端] 监听到与 {} 发生异常并断开连接",getURI().getHost(),ex);
        this.listener.onError(ex);
    }
}
